#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/xfeatures2d.hpp>

using namespace cv;
using namespace xfeatures2d;
using namespace std;

class CAD {
public:
    Mat sourceImg;
    vector<Mat> contours;

    CAD() {

    }
};

int main()
{
    CAD cad;
    cad.sourceImg = imread("../../resource/image/circuit/cad.jpg", CAP_MODE_GRAY);
    threshold(cad.sourceImg, cad.sourceImg, 200, 255, THRESH_BINARY_INV);
//    imshow("sourceImg", cad.sourceImg);
//    dilate(cad.sourceImg, cad.sourceImg, Mat(), Point(-1, -1));
    //先去除文字
    Mat contoursImg = cad.sourceImg.clone().setTo(0);
    findContours(cad.sourceImg.clone(), cad.contours,
                 CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
    drawContours(contoursImg, cad.contours, -1, Scalar(255));
    imshow("contoursImg", contoursImg);
    cout << cad.contours.size() << endl;

    vector<Rect> contoursRect;
    Mat contoursRectImg = cad.sourceImg.clone().setTo(0);
    Mat leastContoursRectImg = contoursRectImg.clone();
    float allRectsAverageArea = 0.0;
    for (size_t i = 0; i < cad.contours.size(); i++) {
        contoursRect.push_back(boundingRect(cad.contours[i]));      //添加最小外接矩形
        rectangle(contoursRectImg, contoursRect[i], Scalar(255));   //画出矩形
        allRectsAverageArea += contoursRect[i].area();              //计算平均面积
    }
    allRectsAverageArea /= contoursRect.size(); //平均面积
    float minEdgeLength = pow(allRectsAverageArea, 0.5);    //开方后的最小边
    Mat uselessImg = cad.sourceImg.clone().setTo(0);    //无用图
    for (size_t i = 0; i < cad.contours.size(); i++) {
        if (contoursRect[i].height < minEdgeLength && contoursRect[i].width < minEdgeLength) {
            rectangle(leastContoursRectImg, contoursRect[i], Scalar(255));   //画出矩形
            cad.sourceImg(contoursRect[i]).copyTo( uselessImg(contoursRect[i]) );
        }
    }

    imshow("sourceImg", cad.sourceImg);
    imshow("contoursRectImg", contoursRectImg);
    imshow("leastContoursRectImg", leastContoursRectImg);
    imshow("uselessImg", uselessImg);

//    erode(cad.sourceImg, cad.sourceImg, Mat(), Point(-1, -1));
//    erode(uselessImg, uselessImg, Mat(), Point(-1, -1));

    Mat usefullImg = cad.sourceImg - uselessImg;
//    erode(usefullImg, usefullImg, Mat(), Point(-1, -1));
    imshow("Test", usefullImg);
    //获取文字图




    waitKey(0);
    destroyAllWindows();
    return 0;
}
